package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.cskaoyan.order.constant.OrderConstants.ORDER_ID;
import static com.cskaoyan.order.constant.OrderConstants.ORDER_ITEM_ID;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext= (CreateOrderContext) context;
        //插入订单表
        Order order = new Order();
        // String orderId = globalIdGeneratorUtil.getNextSeq(ORDER_ID, 1);

        // String orderId = UUID.randomUUID().toString();

        //全局id生成器(发号器)
        order.setOrderId(createOrderContext.getUniqueKey());
        //将生成的订单id放入上下文对象context
        createOrderContext.setOrderId(createOrderContext.getUniqueKey());

        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getUserName());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        orderMapper.insert(order);
        //插入订单商品关联表
        List<Long> buyProductIds = new ArrayList<>();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();

            // String orderItemId = UUID.randomUUID().toString();
            String orderItemId = globalIdGeneratorUtil.getNextSeq("order_item_id", 1);

            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(createOrderContext.getUniqueKey());
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());
            BigDecimal total = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setTotalFee(total.doubleValue());


            Long productId = cartProductDto.getProductId();
            Stock stock = stockMapper.selectStock(productId);

            if (stock.getStockCount()<cartProductDto.getProductNum()){
                throw new BizException(OrderRetCode.ORDER_THAN_STOCK_COUNT.getCode(),
                        cartProductDto.getProductName()+OrderRetCode.ORDER_THAN_STOCK_COUNT.getMessage());
            }


            //已锁定库存
            orderItem.setStatus(1);
            buyProductIds.add(cartProductDto.getProductId());

            int effected = orderItemMapper.insert(orderItem);
            if (effected<1){
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                        OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }

        }
        createOrderContext.setOrderId(createOrderContext.getUniqueKey());
        createOrderContext.setBuyProductIds(buyProductIds);
        createOrderContext.setBuyerNickName(createOrderContext.getUserName());

        return true;
    }

}
